package com.lt.test.provider.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.lt.test.api.SPLOrderService;
import com.lt.test.common.exception.CustomException;
import com.lt.test.common.util.CustomUtil;
import com.lt.test.entity.DTO.*;
import com.lt.test.entity.QueryModel.PageFilter;
import com.lt.test.entity.QueryModel.PageQueryModel;
import com.lt.test.provider.mapper.SPLOrderMapper;
import com.lt.test.provider.mapper.UserMapper;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by zhengchuan on 2017/3/14.
 */
@Service(version = "1.0.0")
public class SPLOrderServiceImpl implements SPLOrderService {

    private static final Logger logger = LoggerFactory.getLogger(SPLOrderServiceImpl.class);

    @Resource
    private SPLOrderMapper sPLOrderMapper;
    @Resource
    private UserMapper userMapper;
    @Override
    public PageDTO<SPLOrderDTO> findSPLOrderByPage(Integer page, Integer pageSize, String sortedKey, String sortedValue, String filters) throws CustomException {
        Long beginNum = (long) ((page - 1) * pageSize + 1);
        Long endNum = beginNum + pageSize - 1;

        PageQueryModel pageQueryModel = new PageQueryModel();
        pageQueryModel.setBeginNum(beginNum);
        pageQueryModel.setEndNum(endNum);

        if("orderTimeStr".equals(sortedKey)) {
            pageQueryModel.setSortName("SPLO.ORDER_DATE");
        }else {
            pageQueryModel.setSortName("SPLO.STATE_DATE");
        }
        pageQueryModel.setSortOrder(("asc".equals(sortedValue) ? "asc" : "desc"));//防止sql注入

        if(filters != null && !filters.trim().equals("")) {
            JSONObject jsonObject = JSONObject.fromObject(filters);
            JSONArray jsonArray = (JSONArray) jsonObject.get("rules");
            List<PageFilter> filterList = new ArrayList<>();
            for(int i = 0; i < jsonArray.size(); i++) {
                JSONObject result = (JSONObject) jsonArray.get(i);
                if("channelName".equals(result.get("field")) && StringUtils.isNotBlank(result.getString("data"))){
                    PageFilter filter = new PageFilter();
                    filter.setFilterName("SO.CUST_CODE");
                    filter.setFilterType("LIKE");
                    filter.setFilterValue("'%"+result.getString("data")+"%'");
                    filterList.add(filter);
                }
                if("slsmanName".equals(result.get("field")) && StringUtils.isNotBlank(result.getString("data")) && !result.getString("data").equals("-1")){
                    PageFilter filter = new PageFilter();
                    filter.setFilterName("SO.ORDER_NO");
                    filter.setFilterType("LIKE");
                    filter.setFilterValue("'%"+result.getString("data")+"%'");
                    filterList.add(filter);
                }
            }
            pageQueryModel.setFilters(filterList);
        }
        List<SPLOrderDTO> sPLOrderDTOList = null;
        int recordCount = 0;
        try {
            sPLOrderDTOList = sPLOrderMapper.findSPLOrderByPage(pageQueryModel);
            recordCount = sPLOrderMapper.getSPLOrderCount(pageQueryModel);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("获取烟草客户订单列表失败");
        }
        PageDTO<SPLOrderDTO> result = new PageDTO<>(page, pageSize, sPLOrderDTOList, recordCount);
        return result;
    }

    @Override
    public List<OrderPayInfoDTO> getPayInfo(String orderId) throws CustomException {
        List<OrderPayInfoDTO> result = null;
        try {
            result = sPLOrderMapper.getPayInfo(orderId);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("Dubbo异常");
        }
        return result;
    }

    @Override
    public List<SPLOrderDTO> findSPLOrderByLsatCreateTime(String lastOrderTime, ActiveUser activeUser) throws CustomException {

        List<SPLOrderDTO> result;
        Map<String, String> params = new HashedMap(3, 1.0F);

        params.put("empName", activeUser.getEmpName());
        String quXianName = activeUser.getQuXianName();
        if (quXianName != null && !quXianName.equals("")) {
            try {
                params.put("parentChannelId", sPLOrderMapper.getIdByChannleName(quXianName));
            } catch (Exception e) {
                e.printStackTrace();
                throw new CustomException("获取区县失败");
            }
        }
        params.put("channelName", activeUser.getChannelName());
        params.put("realChannelName", activeUser.getRealChannelName());
        //初次获取
        if (lastOrderTime == null || "".equals(lastOrderTime)) {

            try {
                result = sPLOrderMapper.findTenSPLOrder(params);
            } catch (Exception e) {
                e.printStackTrace();
                throw new CustomException("获取初始化十条订单失败");
            }
        }else {
            params.put("lastOrderTime",lastOrderTime);
            try {
                result = sPLOrderMapper.findSPLOrderByLastOrderTime(params);
            } catch (Exception e) {
                e.printStackTrace();
                throw new CustomException("根据最后更新时间获取订单失败");
            }
        }
        return result;
    }

    @Override
    public Map<String, Object> findSPLOrderDayData(ActiveUser activeUser, String success) throws CustomException {
        Calendar ca = Calendar.getInstance();
        ca.setTime(new Date());
        ca.add(Calendar.DATE, -7);
        Date firstDay = ca.getTime();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        String firstDayStr = sf.format(firstDay);
        //firstDayStr = "2016-11-19";

        try {
            Map<String, String> params = new HashedMap(2, 1.0F);
            params.put("firstDayStr",firstDayStr);
            params.put("channelCodePreFive", CustomUtil.getChannelCodePreFive(activeUser.getChannelName()));
            params.put("empName",activeUser.getEmpName());
            params.put("realChannelName",activeUser.getRealChannelName());
            params.put("quXianName",activeUser.getQuXianName());
            params.put("success",success);
            List<Map<String,Object>>SPLOrderDayList = sPLOrderMapper.findSPLOrderDayData(params);
            Map<String, Object> result = new HashedMap(3,1.0F);
            List days = new ArrayList(10);
            List prices = new ArrayList(10);
            List sums = new ArrayList(10);
            for (Map<String,Object> SPLOrderDay : SPLOrderDayList ) {
                days.add(SPLOrderDay.get("dayNum"));

                Double price = Double.valueOf(SPLOrderDay.get("priceSum").toString());
                Double price1 = price/10000;
                BigDecimal b   =   new   BigDecimal(price1);
                Double f1 = b.setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue();
                for (int i = 3 ; i < 10 ; i++){
                    if (f1>0.00){
                        break;
                    }
                    f1 = b.setScale(i, BigDecimal.ROUND_HALF_UP).doubleValue();
                }
                prices.add(f1);

                sums.add(SPLOrderDay.get("countNum"));
            }
            result.put("dayNums",days);
            result.put("priceSums",prices);
            result.put("countNums",sums);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("按天查询订单统计失败");
        }
    }

    @Override
    public Map<String, Object> findSPLOrderMonthData(ActiveUser activeUser, String success) throws CustomException {
        Calendar ca = Calendar.getInstance();
        ca.setTime(new Date());
        ca.add(Calendar.MONTH, -7);
        Date firstDay = ca.getTime();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM");
        String firstDayStr = sf.format(firstDay);
        //firstDayStr = "2015-12";



        try {
            Map<String, String> params = new HashedMap(10, 1.0F);
            params.put("firstDayStr",firstDayStr);

            params.put("channelCodePreFive", CustomUtil.getChannelCodePreFive(activeUser.getChannelName()));
            params.put("empName",activeUser.getEmpName());
            params.put("realChannelName",activeUser.getRealChannelName());
            params.put("quXianName",activeUser.getQuXianName());

            params.put("success",success);
            List<Map<String,Object>>SPLOrderDayList = sPLOrderMapper.findSPLOrderMonthData(params);
            Map<String, Object> result = new HashedMap(3,1.0F);
            List days = new ArrayList(10);
            List prices = new ArrayList(10);
            List sums = new ArrayList(10);
            for (Map<String,Object> SPLOrderDay : SPLOrderDayList ) {
                days.add(SPLOrderDay.get("dayNum"));

                Double price = Double.valueOf(SPLOrderDay.get("priceSum").toString());
                Double price1 = price/10000;
                BigDecimal b   =   new   BigDecimal(price1);
                Double f1 = b.setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue();
                for (int i = 3 ; i < 10 ; i++){
                    if (f1>0.00){
                        break;
                    }
                    f1 = b.setScale(i, BigDecimal.ROUND_HALF_UP).doubleValue();
                }
                prices.add(f1);

                sums.add(SPLOrderDay.get("countNum"));
            }
            result.put("dayNums",days);
            result.put("priceSums",prices);
            result.put("countNums",sums);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("按月查询订单统计失败");
        }
    }

    @Override
    public Map<String, Object> findSPLOrderYearData(ActiveUser activeUser, String success) throws CustomException {
        Calendar ca = Calendar.getInstance();
        ca.setTime(new Date());
        ca.add(Calendar.WEEK_OF_YEAR, -7);
        Date firstDay = ca.getTime();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-ww");
        String firstDayStr = sf.format(firstDay);
        //firstDayStr = "2015-21";

        try {
            Map<String, String> params = new HashedMap(2, 1.0F);
            params.put("firstDayStr",firstDayStr);
            params.put("channelCodePreFive", CustomUtil.getChannelCodePreFive(activeUser.getChannelName()));
            params.put("empName",activeUser.getEmpName());
            params.put("realChannelName",activeUser.getRealChannelName());
            params.put("quXianName",activeUser.getQuXianName());
            params.put("success",success);
            List<Map<String,Object>>SPLOrderDayList = sPLOrderMapper.findSPLOrderYearData(params);
            Map<String, Object> result = new HashedMap(3,1.0F);
            List days = new ArrayList(10);
            List prices = new ArrayList(10);
            List sums = new ArrayList(10);
            for (Map<String,Object> SPLOrderDay : SPLOrderDayList ) {
                days.add(SPLOrderDay.get("dayNum"));

                Double price = Double.valueOf(SPLOrderDay.get("priceSum").toString());
                Double price1 = price/10000;
                BigDecimal b   =   new   BigDecimal(price1);
                Double f1 = b.setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue();
                for (int i = 3 ; i < 10 ; i++){
                    if (f1>0.00){
                        break;
                    }
                    f1 = b.setScale(i, BigDecimal.ROUND_HALF_UP).doubleValue();
                }
                prices.add(f1);

                sums.add(SPLOrderDay.get("countNum"));
            }
            result.put("dayNums",days);
            result.put("priceSums",prices);
            result.put("countNums",sums);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("按月查询订单统计失败");
        }
    }

    @Override
    public List<SPLOrderDTO> getOrderByTime(Map<String, Object> paramrs) throws CustomException {
        String beginTime = null;
        if (paramrs.get("beginTime") == null || paramrs.get("beginTime").toString().equals("")) {
            Calendar ca = Calendar.getInstance();
            ca.setTime(new Date());
            ca.add(Calendar.MONTH, -1);
            Date firstDay = ca.getTime();
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
            beginTime = sf.format(firstDay);
        }else {
            beginTime = paramrs.get("beginTime").toString();
        }

        Map<String, String> params = new HashedMap(3, 1.0F);
        params.put("payStatus",paramrs.get("payStatus")== null ? null : paramrs.get("payStatus").toString());
        params.put("orderId",paramrs.get("orderId")== null ? null : paramrs.get("orderId").toString());
        params.put("orderLevel",paramrs.get("orderLevel")== null ? null : paramrs.get("orderLevel").toString());
        params.put("beginTime",beginTime);
        params.put("endTime",paramrs.get("endTime")== null ? null : paramrs.get("endTime").toString());
        params.put("channelNamePage",paramrs.get("channelNamePage")== null ? null : paramrs.get("channelNamePage").toString());
        params.put("parentChannelId",paramrs.get("parentChannelId") == null ? null : paramrs.get("parentChannelId").toString());
        params.put("channelName",paramrs.get("channelName") == null ? null : paramrs.get("channelName").toString());
        params.put("custName",paramrs.get("custCode") == null ? null : paramrs.get("custCode").toString());
        params.put("orderBeginDate",paramrs.get("orderBeginDate") == null ? null : paramrs.get("orderBeginDate").toString());
        params.put("orderEndDate",paramrs.get("orderEndDate") == null ? null : paramrs.get("orderEndDate").toString());
        params.put("empName", (paramrs.get("empName") == null || "".equals(paramrs.get("empName").toString()) ? null : paramrs.get("empName").toString()));


        String quXianName = paramrs.get("quXianName") == null ?  null : paramrs.get("quXianName").toString();
        if (quXianName != null && !quXianName.equals("")) {
            try {
                params.put("parentChannelId", sPLOrderMapper.getIdByChannleName(quXianName));
            } catch (Exception e) {
                e.printStackTrace();
                throw new CustomException("获取区县失败");
            }
        }

        try {
            return sPLOrderMapper.getOrderByBeginTimeAndEndTime(params);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("根据时间查询烟草订单记录失败");
        }

    }

    @Override
    public String getIdByChannleName(String quXianName) throws CustomException {
        try {
            return sPLOrderMapper.getIdByChannleName(quXianName);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("根据channel名称查询id失败");
        }
    }

    @Override
    public String getAllChannelIdByQuXianName(String quXianName) throws CustomException{
        List<String> allChannleIds = null;
        if (quXianName != null && !quXianName.equals("")) {
            try {
                String quXianId = sPLOrderMapper.getIdByChannleName(quXianName);
                if (quXianId == null) {
                    allChannleIds = new ArrayList<>();
                    allChannleIds.add("noData");
                    throw new CustomException("没有查到"+quXianName+"对应的Id");
                }else {
                    allChannleIds  = sPLOrderMapper.getChannelIdsByQuXianId(quXianId);
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw new CustomException("获取quXianId失败");
            }
        }

        StringBuffer resultB = new StringBuffer("");
        String result = "";
        if (allChannleIds != null && allChannleIds.size() > 0) {
            for (String s : allChannleIds) {
                resultB.append("'" + s + "',");
            }
            result = resultB.substring(0,resultB.length()-1);
        }

        return result;
    }

    @Override
    public Map<String, List<String>> findSPLOrderStatisticsDayData(Map<String, String> stringMap) {
        Calendar ca = Calendar.getInstance();
        ca.setTime(new Date());
        ca.add(Calendar.DATE, -7);
        Date firstDay = ca.getTime();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        String firstDayStr = sf.format(firstDay);
        //firstDayStr = "2016-11-19";

        stringMap.put("firstDayStr",firstDayStr);
        stringMap.put("formatStr","'yyyy-mm-dd'");

        List<Map<String,String>> SPLOrderDayList = sPLOrderMapper.findSPLOrderStatisticsData(stringMap);

        return disposeSPLOrderStatisticsData(SPLOrderDayList);

    }

    @Override
    public Map<String, List<String>> findSPLOrderStatisticsWeekData(Map<String, String> stringMap) {
        Calendar ca = Calendar.getInstance();
        ca.setTime(new Date());
        ca.add(Calendar.WEEK_OF_YEAR, -7);
        Date firstDay = ca.getTime();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-ww");
        String firstDayStr = sf.format(firstDay);
        //firstDayStr = "2015-21";

        stringMap.put("firstDayStr",firstDayStr);
        stringMap.put("formatStr","'yyyy-ww'");

        List<Map<String,String>> SPLOrderDayList = sPLOrderMapper.findSPLOrderStatisticsData(stringMap);

        return disposeSPLOrderStatisticsData(SPLOrderDayList);
    }

    @Override
    public Map<String, List<String>> findSPLOrderStatisticsMonthData(Map<String, String> stringMap) {
        Calendar ca = Calendar.getInstance();
        ca.setTime(new Date());
        ca.add(Calendar.MONTH, -7);
        Date firstDay = ca.getTime();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM");
        String firstDayStr = sf.format(firstDay);
        //firstDayStr = "2015-12";

        stringMap.put("firstDayStr",firstDayStr);
        stringMap.put("formatStr","'yyyy-mm'");

        List<Map<String,String>> SPLOrderDayList = sPLOrderMapper.findSPLOrderStatisticsData(stringMap);

        return disposeSPLOrderStatisticsData(SPLOrderDayList);
    }


    private Map<String, List<String>> disposeSPLOrderStatisticsData(List<Map<String,String>> sPLOrderStatisticsDataList) {
        Map<String, List<String>> result = new HashedMap(3,1.0F);

        List<String> days = new ArrayList(10);
        List<String> prices = new ArrayList(10);
        List<String> sums = new ArrayList(10);

        for (Map<String,String> SPLOrderDay : sPLOrderStatisticsDataList ) {

            days.add(SPLOrderDay.get("dayNum"));
            sums.add(SPLOrderDay.get("countNum"));

            Double price = Double.valueOf(SPLOrderDay.get("priceSum").toString());

            Double price1 = price/10000;

            BigDecimal b   =   new   BigDecimal(price1);
            Double f1 = b.setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue();
            for (int i = 3 ; i < 10 ; i++){
                if (f1>0.00){
                    break;
                }
                f1 = b.setScale(i, BigDecimal.ROUND_HALF_UP).doubleValue();
            }
            prices.add(f1.toString());


        }

        result.put("dayNum",days);
        result.put("priceSum",prices);
        result.put("countNum",sums);

        return result;
    }

    @Override
    public PageDTO<Map<String, String>> findSPLOrderByPage(Map<String, String> stringMap) {
        Integer page = Integer.valueOf(stringMap.get("page"));
        Integer pageSize = Integer.valueOf(stringMap.get("pageSize"));

        Integer beginNum =  (page - 1) * pageSize + 1;
        Integer endNum = beginNum + pageSize - 1;

        stringMap.put("beginNum", beginNum.toString());
        stringMap.put("endNum", endNum.toString());

        List<Map<String, String>> data  = sPLOrderMapper.findSPLOrderByPageM(stringMap);
        int recordCount = sPLOrderMapper.getSPLOrderCountM(stringMap);
        PageDTO<Map<String, String>> result = new PageDTO<>(page, pageSize, data, recordCount);
        return result;
    }
}
